package com.jdone.compus.config;

//

import com.jdone.compus.security.JwtAuthenticationFilter;
import com.jdone.compus.service.CustomUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.HttpFirewall;
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomUserDetailsService customUserDetailsService;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/auth/**").permitAll()
                .antMatchers("/compus/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/doc.html").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/gift-submissions/**").permitAll()
                .antMatchers("/orders/**").permitAll()
                .antMatchers("/api/proxy/**").permitAll()
                .antMatchers("/payment/**").permitAll()
                .antMatchers("/student-whitelist/**").permitAll()

                .antMatchers("/images/**").permitAll()
                .antMatchers("/blow/**").permitAll()
                .antMatchers("/blow/**/wechat/**").permitAll()
                .antMatchers("/blow/login/**").permitAll()
                .antMatchers("/blow/proxy/**").permitAll()
                .antMatchers("/blow/repairs/**").permitAll()
                .antMatchers("/blow/api/saas/**").permitAll()
                .antMatchers("/wechat/**").permitAll()
                .antMatchers("/api/proxy/**").permitAll()
                .antMatchers("/blow/quick_durations/findAll").permitAll()
                .antMatchers("/blow/usage-records/wechat/**").permitAll()
                .antMatchers("/internal/reconcile/**").permitAll()


                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors().and() // Enable CORS
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowedHeaders("*");
            }
        };
    }

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);
        firewall.setAllowUrlEncodedDoubleSlash(true);
        return firewall;
    }
}


//
//@Configuration
//@EnableWebSecurity
//@RequiredArgsConstructor
//public class SecurityConfig extends WebSecurityConfigurerAdapter {
//
//    private final JwtAuthenticationFilter jwtAuthenticationFilter;
//    private final CustomUserDetailsService customUserDetailsService;
//
/// *    *
// * 禁用容器对 JwtAuthenticationFilter 的自动 servlet 注册，避免与 Spring Security 的 filter 链重复注册冲突。
// * 仍然保持该 Filter 作为一个 Spring Bean（可通过 @Component 注入），由 Spring Security 使用 addFilterBefore(...) 放入安全链。
// */
//    @Bean
//    public FilterRegistrationBean<JwtAuthenticationFilter> disableAutoRegister(JwtAuthenticationFilter filter) {
//        FilterRegistrationBean<JwtAuthenticationFilter> registration = new FilterRegistrationBean<>(filter);
//        registration.setEnabled(false); // 关键：禁止容器自动注册
//        return registration;
//    }
//
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http
//                // ---- 授权规则 ----
//                .authorizeRequests()
//                .antMatchers("/api/auth/**").permitAll()
//                .antMatchers("/compus/**").permitAll()
//                .antMatchers("/gift-submissions/**").permitAll()
//                .antMatchers("/orders/**").permitAll()
//                .antMatchers("/api/proxy/**").permitAll()
//                .antMatchers("/payment/**").permitAll()
//                .antMatchers("/student-whitelist/**").permitAll()
//                .antMatchers("/images/**").permitAll()
//
//
//                .antMatchers("/images/**").permitAll()
//                .antMatchers("/blow/**/wechat/**").permitAll()
//                .antMatchers("/blow/login/**").permitAll()
//                .antMatchers("/blow/proxy/**").permitAll()
//                .antMatchers("/blow/repairs/**").permitAll()
//                .antMatchers("/blow/api/saas/**").permitAll()
//                // 禁止访问 Swagger / API 文档
//                .antMatchers(
//                        "/v2/api-docs",
//                        "/v3/api-docs",
//                        "/swagger-resources/**",
//                        "/swagger-ui.html",
//                        "/swagger-ui/**",
//                        "/doc.html",
//                        "/swagger-resources/configuration/ui",
//                        "/swagger-resources/configuration/security"
//                ).denyAll()
//                .anyRequest().authenticated()
//                .and()
//                // 无状态会话
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                .and()
//                // 不启用 .cors()，而使用自定义 BlockCorsFilter（放在 UsernamePasswordAuthenticationFilter 之前）
//                .addFilterBefore(new BlockCorsFilter(), UsernamePasswordAuthenticationFilter.class)
//                // 把你的 JwtAuthenticationFilter 放在 UsernamePasswordAuthenticationFilter 之前
//                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
//
//    }
///*
//    *
// * 简单的阻断跨源请求过滤器（如果请求有 Origin 且与本 Host 不同则拒绝）*/
//
//    static class BlockCorsFilter extends OncePerRequestFilter {
//        @Override
//        protected void doFilterInternal(HttpServletRequest request,
//                                        HttpServletResponse response,
//                                        FilterChain filterChain) throws ServletException, IOException {
//            String origin = request.getHeader("Origin");
//            if (origin != null && !origin.isEmpty()) {
//                String scheme = request.getScheme(); // http 或 https
//                String host = request.getHeader("Host"); // host[:port]
//                String expectedOrigin = scheme + "://" + host;
//                if (!expectedOrigin.equalsIgnoreCase(origin)) {
//                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Cross-origin requests are not allowed");
//                    return;
//                }
//            }
//            filterChain.doFilter(request, response);
//        }
//    }
//
//   }

